//
//  WCG_O_Detail_DetailProviderViewController.m
//  Project_B
//
//  Created by 黑黑 on 15/11/27.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "WCG_O_Detail_DetailProviderViewController.h"

@interface WCG_O_Detail_DetailProviderViewController () <UIWebViewDelegate, UMSocialUIDelegate, UIScrollViewDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (nonatomic, assign) BOOL like;
@property (nonatomic, strong) NSMutableArray *likeArr;
@property (nonatomic, strong) NSMutableArray *unlikeArr;

@end

@implementation WCG_O_Detail_DetailProviderViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createWebViewWithFrame:self.view.bounds URL:[NSURL URLWithString:self.link]];
    self.webView.delegate = self;
    self.webView.scrollView.delegate = self;
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.emptyDataSetDelegate = self;
    self.webView.scrollView.emptyDataSetSource = self;
    [self loadNightMBProgress];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIView animateWithDuration:1 animations:^{
        UIView *temp = self.tabBarController.view.subviews[2];
        temp.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 49);
    }];
    
    self.navigationController.navigationBarHidden = YES;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SpecialModel" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@", self.titleStr];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"空");
    }
    if (fetchedObjects.count != 0) {
        for (SpecialModel *spe in fetchedObjects) {
            if (![spe.title isEqualToString:self.titleStr]) {
                self.like = NO;
            }else{
                self.like = YES;
            }
        }
    }
    if (!self.like) {
        [self createButtomLikeButton];
    }else
    {
        [self createButtomUnLikeButton];
    }
    
    [self.backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.likeBtn addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.repostBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
}



- (void)backAction:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)likeAction:(UIButton *)sender
{
    if (self.like) {
        [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"bottom_btn_like_active"] forState:UIControlStateNormal];
        [self getDisLikeImage];
        self.flashImage.animationDuration = 0.5;
        self.flashImage.animationImages = self.unlikeArr;
        self.flashImage.animationRepeatCount = 1;
        [self.flashImage startAnimating];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"SpecialModel" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@", self.titleStr];
        [fetchRequest setPredicate:predicate];
        // Specify how the fetched objects should be sorted
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            NSLog(@"空空空~");
        }
        for (SpecialModel *s in fetchedObjects) {
            [self.manager.managedObjectContext deleteObject:s];
        }
        [self.manager saveContext];
    }else
    {
        [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"bottom_btn_liked"] forState:UIControlStateNormal];
        [self getLikeImage];
        self.flashImage.animationDuration = 0.5;
        self.flashImage.animationRepeatCount = 1;
        self.flashImage.animationImages = self.likeArr;
        [self.flashImage startAnimating];
        // 添加
        SpecialModel *special = [NSEntityDescription insertNewObjectForEntityForName:@"SpecialModel" inManagedObjectContext:self.manager.managedObjectContext];
        special.title = self.detailModel.title;
        special.type = @"prolike";
        special.content_update_time = self.detailModel.author;
        special.share_text = self.detailModel.link;
        special.title_font = self.detailModel.image[@"raw"];
        [self.manager saveContext];
    }
    self.like = !self.like;
}

#pragma mark - 获取动图组
#if 0

- (void)getimgArrR
{
    self.imgArrR = [NSMutableArray array];
    for (NSInteger i = 0; i < 30; i++) {
        NSString *name = [NSString stringWithFormat:@"footRight_%02ld@2x", i];
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"jpg"];
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        [self.imgArrR addObject:img];
    }
    - (void)tapActionRightFoot
    {
        [self getimgArrR];
        self.imgView.animationDuration = 2;
        self.imgView.animationImages = self.imgArrR;
        self.imgView.animationRepeatCount = 1;
        [self.imgView startAnimating];
    }
}
#endif

- (void)getDisLikeImage
{
    self.unlikeArr = [NSMutableArray array];
    for (NSInteger i = 1; i <= 8; i++) {
        NSString *name = [NSString stringWithFormat:@"dislike_%ld@2x", i];
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        [self.unlikeArr addObject:img];
    }
}

- (void)getLikeImage
{
    self.likeArr = [NSMutableArray array];
    for (NSInteger i = 1; i <= 14; i++) {
        NSString *name = [NSString stringWithFormat:@"liked_%02ld@2x", i];
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        [self.likeArr addObject:img];
    }
}

- (void)shareAction:(UIButton *)sender
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"563c60e267e58e6ae1000680"
                                      shareText:self.detailModel.title
                                     shareImage:nil
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,nil]
                                       delegate:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static CGFloat y;
    if (scrollView.contentOffset.y > y) {
        [UIView animateWithDuration:1 animations:^{
            self.backBtn.alpha = 0;
            self.repostBtn.alpha = 0;
            self.likeBtn.alpha = 0;
        }];
        y = scrollView.contentOffset.y;
    }
    if (scrollView.contentOffset.y < y) {
        [UIView animateWithDuration:1 animations:^{
            self.backBtn.alpha = 0.8;
            self.repostBtn.alpha = 0.8;
            self.likeBtn.alpha = 0.8;
        }];
        y = scrollView.contentOffset.y;
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"开始加载");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"结束加载");
    [self.hud removeFromSuperview];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"%@", error);
}

#pragma mark - 空白数据时的代理方法
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return [UIImage imageNamed:@"icon-search-article"];
}

#pragma mark - 当数据为空时显示的字符
-(NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"数据走丢啦";
    NSDictionary *str = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0f]};
    return [[NSAttributedString alloc] initWithString:text attributes:str];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
